from django.shortcuts import render,HttpResponse,reverse
from django.contrib.auth.hashers import make_password, check_password
from ..models import *
from django.http import JsonResponse
import os
from django.contrib.auth.decorators import permission_required


#用户列表
@permission_required('myadmin.show_Users',raise_exception=True)
def user_list(request):

    #接收搜索框传来的数据  如果没有则默认为None
    keyword=request.GET.get('keyword',None)
    types=request.GET.get('types',None)

    #默认查询所有数据
    #print(Users.objects.all())
    data=Users.objects.all()

    #如果有搜索条件
    #判断types是否是全部
    if types=='all':
        from django.db.models import Q
        data=Users.objects.filter(Q(id__contains=keyword)|Q(nikename__contains=keyword)|Q(phone__contains=keyword)|Q(email__contains=keyword))
    elif types:
        #如果不是all 并且是不假值 则进入这个条件
        #通过拼接字典的方式 把types+__contains  拼成 id__contains:keyword 这样的 字典格式
        search={types+'__contains':keyword}
        #把data()对象 的值进行过滤  条件是serach 字典中值
        data=data.filter(**search)

    #导入django分页模块
    from django.core.paginator import Paginator

    #实例化对象 并且获取获取总页数
    p=Paginator(data,10)

    #获取当前页码数 如果没有传递get  默认是1
    pageindex=request.GET.get('page',1)

    #把导入的模块pag  使用对象p.page() 传递当前页数 默认是1  得到的结果是<userlist 1 of 15>
    #意思是当前页码是1页 总共15页
    user_list=p.page(pageindex)


    context={'userlist':user_list}
    print(context)
    return render(request,'myadmin/user_list.html',context)



#用户添加页面  用户登录界面判断
@permission_required('myadmin.create_Users',raise_exception=True)
def user_add(request):
    sessions=request.session.get('user', default=None)
    if sessions:
        return render(request,'myadmin/user_add.html')
    else:
        return HttpResponse('<script>alert("请先登录");location.href="' + reverse('user_log') + '";</script>')

#用户添加执行
@permission_required('myadmin.create_Users',raise_exception=True)
def user_insert(request):
    #接受表单 不包含img
    data=request.POST.dict()
    data.pop("csrfmiddlewaretoken")
    data['password']=make_password(data['password'],None,'pbkdf2_sha256')
    #接受头像上传
    myfile=request.FILES.get('pic',None)
    if not myfile:
        return HttpResponse('<script>alert("没有选择头像上传");history.back(-1);</script>')

    #处理头像上传
    data['pic_url']=uploads_pic(myfile)
    #print(data)
    try:
        ob=Users(**data)
        ob.save()
        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('index')+'";</script>')
    except:
        return HttpResponse('<script>alert("添加失败");history.back(-1);</script>')
    #print(data)
    #return HttpResponse('1')
#用户编辑
@permission_required('myadmin.edit_Users',raise_exception=True)
def user_edit(request):
    #print(request.GET.get('id'))
    #会员信息更新
    if request.method=='POST':
        uid = request.POST['uid']
        ob = Users.objects.get(id=uid)

        #更新密码
        if request.POST.get('password', None):
            ob.password=make_password(request.POST['password'],None, 'pbkdf2_sha256')

        #更新头像
        myfile=request.FILES.get('pic',None)
        if myfile:
            if os.path.isfile('.'+ob.pic_url):
                os.remove('.'+ob.pic_url)
            ob.pic_url=uploads_pic(myfile)
        #更新其他信息
        ob.nikename=request.POST.get('nikename')
        ob.email = request.POST.get('email')
        ob.phone = request.POST.get('phone')
        if(request.POST.get('age')):
            ob.age = request.POST.get('age')
        ob.sex = request.POST.get('sex')
        ob.save()
        return HttpResponse('<script>alert("更新成功");location.href="/myadmin/user_list/";</script>')

    else:
        id=request.GET.get('id')
        data=Users.objects.get(id=id)
        #必须使用values 否则返回的是{1:{对象}}
        return render(request,'myadmin/user_edit.html',{'data':data})
    #return HttpResponse('user_edit')

#图片名修改
def uploads_pic(myfile):
    try:
        import time
        import random
        randnum=str(random.randint(0,1000))
        #                           先把文件名分割成列表 删除列表中的后缀 并且把删除的后缀返回
        filename=str(time.time())+randnum+'.'+myfile.name.split('.').pop()
        destination=open('./static/uploads/'+filename,"wb+")
        #把文件切割成多个快
        for i in myfile.chunks():
            destination.write(i)

        destination.close()
        return '/static/uploads/'+filename
    except:
        return False

#用户状态修改
@permission_required('myadmin.edit_Users',raise_exception=True)
def user_status(request):
    #print(request.GET.get('uid'))
    ob=Users.objects.get(id=request.GET.get('uid'))
    ob.status=request.GET.get('status')
    ob.save()
    return JsonResponse({'msg': '状态更新成功', 'code': 0})

#删除用户
@permission_required('myadmin.remove_Users',raise_exception=True)
def user_del(request):
    ob = Users.objects.get(id=request.GET.get('id'))
    ob.delete()
    return HttpResponse('<script>alert("删除成功");location.href="/myadmin/user_list/";</script>')

#编辑
@permission_required('myadmin.edit_Users',raise_exception=True)
def user_nike(request):
    nikename=request.GET.get('nikename')
    id=request.GET.get('uid')
    #print(nikename,id)
    ob=Users.objects.get(id=id)
    ob.nikename=nikename
    ob.save()
    return HttpResponse('1')



